<template>
  <div class="bg-white pt-[24px] page-submit-order">
    <div class="m-auto w"></div>

    <div class="w m-auto flex gap-[16px] relative pb-[350px]">
      <div class="flex-1">
        <div class="mb-[16px]">
          <div class="text-[18px] font-[500] mb-[8px]">
            {{ $t("submitOrder.购买方式") }}
          </div>
          <n-radio-group
            v-model:value="formData.logisticsSelfCare"
            name="buyWay"
            @update:value="handleChangeLogisticsSelfCare"
          >
            <div class="flex flex-col gap-[8px] pl-[32px]">
              <div>
                <n-radio :value="false">
                  <div class="text-[18px] font-[300] text-[#3D3D3D] mt-[-4px]">
                    {{ $t("submitOrder.alib2b方式") }}
                  </div>
                </n-radio>
              </div>
              <div>
                <n-radio :value="true">
                  <div class="text-[18px] font-[300] mt-[-4px]">
                    {{ $t("submitOrder.其它方式") }}
                  </div>
                </n-radio>
              </div>
            </div>
          </n-radio-group>
        </div>
        <div class="mb-[16px]">
          <div class="mb-[8px] text-[18px] font-[500] flex gap-[8px] items-center">
            <div>{{ $t("submitOrder.收货地址") }}</div>
            <n-icon
              class="cursor-pointer"
              @click="onClickSelectAddress"
              :size="16"
              :component="Edit"
            >
            </n-icon>
          </div>
          <div class="pl-[32px] text-[18px] font-[300]">
            <template v-if="address?.fullName">
              {{ address.fullName }},{{ address.phone }},{{ address.address }},{{
                address.areaText
              }},{{ address.cityText }},{{ address.provinceText }},{{ address.postCode }}
            </template>
            <div v-else class="text-[#AAAAAA]" @click="onClickSelectAddress">
              {{ $t("submitOrder.请添加收货地址") }}
              <span class="text-[--main-color] cursor-pointer ml-[8px]">
                {{ $t("button.添加") }}
              </span>
            </div>
          </div>
        </div>

        <div class="mb-[16px]" v-if="!formData.logisticsSelfCare">
          <div class="text-[18px] font-[500] mb-[8px]">
            {{ $t("submitOrder.运输方式") }}
          </div>
          <n-radio-group
            v-model:value="formData.transportType"
            @update:value="calOrderAmount"
            name="transportType"
          >
            <div class="flex flex-col gap-[8px] pl-[32px]">
              <div>
                <n-radio value="0">
                  <div class="text-[18px] font-[300] text-[#3D3D3D] mt-[-4px]">
                    <span>{{ $t("submitOrder.海运") }}</span>
                    <span class="text-[#AAAAAA]">
                      ({{ $t("submitOrder.预计交货时间") }}：45-60 {{ $t("common.天") }})
                    </span>
                  </div>
                </n-radio>
              </div>
              <div>
                <n-radio value="1">
                  <div class="text-[18px] font-[300] text-[#3D3D3D] mt-[-4px]">
                    <span>{{ $t("submitOrder.空运") }}</span>
                    <span class="text-[#AAAAAA]">
                      ({{ $t("submitOrder.预计交货时间") }}：10-15 {{ $t("common.天") }})
                    </span>
                  </div>
                </n-radio>
              </div>
            </div>
          </n-radio-group>
          <n-alert
            class="ml-[54px] rounded-[10px]"
            type="info"
            v-if="formData.transportType == 1"
            :show-icon="false"
          >
            <div class="text-[#4180c6] text-[14px] font-[300]">
              {{ $t("tips.空运提示") }}
            </div>
          </n-alert>
        </div>
        <div class="mb-[16px]">
          <div class="text-[18px] font-[500] mb-[8px]">
            {{ $t("submitOrder.支付方式") }}
          </div>

          <n-radio-group v-model:value="formData.payWay" name="payWay">
            <div class="flex flex-col gap-[8px] pl-[32px]">
              <div>
                <n-radio value="payPal">
                  <div class="text-[18px] font-[300] mt-[-4px]">PayPal</div>
                </n-radio>
              </div>
              <!-- <div>
                <n-radio value="offline">
                  <div class="text-[18px] font-[300] text-[#3D3D3D] mt-[-4px]">
                    <span>Offline Payment</span>
                    <span class="text-[#AAAAAA]">
                      (Payment confirmed by customer service after order submission)</span
                    >
                  </div>
                </n-radio>
              </div> -->
            </div>
          </n-radio-group>
        </div>
        <div class="mb-[16px]" v-if="!formData.logisticsSelfCare">
          <div class="text-[18px] font-[500] mb-[8px]">
            {{ $t("submitOrder.保险") }}（{{ $t("common.可选") }}）
          </div>

          <div class="flex items-center gap-[8px] pl-[32px]">
            <n-checkbox v-model:checked="formData.insure">
              <div class="text-[18px] font-[300] text-[#3D3D3D] mt-[-4px]">
                {{ $t("submitOrder.保险费用说明") }}
              </div>
            </n-checkbox>
          </div>
        </div>

        <div class="mb-[16px]" v-if="!formData.logisticsSelfCare">
          <div class="text-[18px] font-[500] mb-[8px]">
            {{ $t("submitOrder.额外服务") }}（{{ $t("common.可选") }}）
          </div>
          <n-radio-group v-model:value="formData.qualityTesting" name="service">
            <div class="flex flex-col gap-[8px] pl-[32px]">
              <div>
                <n-radio value="40">
                  <div class="text-[18px] font-[300] text-[#3D3D3D] mt-[-4px]">
                    <span>{{ $t("submitOrder.基础检验服务") }}</span>
                    <span class="text-[#AAAAAA]">
                      ({{ $t("submitOrder.基础检验服务说明") }})
                    </span>
                  </div>
                </n-radio>
              </div>
              <div>
                <n-radio value="80">
                  <div class="text-[18px] font-[300] text-[#3D3D3D] mt-[-4px]">
                    <span>{{ $t("submitOrder.功能检查服务") }}</span>
                    <span class="text-[#AAAAAA]">
                      ({{ $t("submitOrder.功能检查服务说明") }})
                    </span>
                  </div>
                </n-radio>
              </div>
              <div>
                <n-radio value="">
                  <div class="text-[18px] font-[300] text-[#3D3D3D] mt-[-4px]">
                    <span>{{ $t("submitOrder.不需要") }}</span>
                  </div>
                </n-radio>
              </div>
            </div>
          </n-radio-group>
        </div>

        <div class="mb-[16px]">
          <div class="text-[18px] font-[500] mb-[8px]">
            {{ $t("submitOrder.商品列表") }}
          </div>
          <tableGoods
            ref="tableGoodsRef"
            v-model:productList="settlementGoods"
            :allow-delete="false"
            @onUpdate="onUpdateProduct"
          ></tableGoods>
        </div>
      </div>
      <div class="w-[336px] h-[200px] sticky top-[86px] transition-all">
        <div class="mb-[16px]">
          <div class="text-[18px] font-[500] mb-[8px]">
            Instrucciones del proceso de pago
          </div>
          <n-steps vertical size="small">
            <n-step>
              <template #title>
                <div class="text-[--main-color]">Pago de Producto</div>
              </template>
              <template #default>
                <div class="text-[#3D3D3D] text-[14px] font-[300]">
                  Pague el costo del producto, el servicio de la plataforma y el costo de
                  transporte interno de China después de crear el pedido.
                </div>
              </template>
            </n-step>
            <n-step>
              <template #title>
                <div class="text-[--main-color]">Pagos Adicionales</div>
              </template>
              <template #default>
                <div class="text-[#3D3D3D] text-[14px] font-[300]">
                  Pague el costo de transporte internacional, el costo del seguro y el
                  costo de inspección después de que el personal lo verifique.
                </div>
              </template>
            </n-step>
          </n-steps>
        </div>
        <div class="bg-[#FFFBF6] p-[18px]">
          <div class="font-[400] text-[18px]">{{ $t("common.汇总") }} （MXN）</div>
          <n-spin :show="amountLoading">
            <div class="font-[300] mt-[8px] text-[16px] flex text-[#3D3D3D]">
              <div class="flex-1">{{ $t("common.商品费用") }}</div>
              <div>
                <money
                  :money="
                    (orderPreviewData.totalAliAmount - orderPreviewData.totalAliPostFee) /
                      100 || 0
                  "
                  :is-cny="showCNY"
                ></money>
                <!-- <money
                  :money="computedGoodsAmount() / 100 || 0"
                  :is-cny="showCNY"
                ></money> -->
              </div>
            </div>
            <div
              class="font-[300] mt-[8px] text-[16px] flex text-[#3D3D3D]"
              v-if="orderPreviewData.totalAliPostFee >= 1"
            >
              <div class="flex items-center flex-1">
                {{ $t("common.阿里运费") }}
                <n-popover trigger="hover" placement="top" :width="400">
                  <template #trigger>
                    <n-icon class="text-[18px] text-[#0866FF] cursor-pointer ml-[8px]">
                      <HelpCircle></HelpCircle>
                    </n-icon>
                  </template>
                  <div class="flex flex-col">
                    Algunos productos tal vez no cumplan con las condiciones de transporte
                    del plan elegido. Después de que el personal verifique, es posible que
                    cambie su plan de transporte. Si se generan costos adicionales, se
                    cobrarán en la segunda etapa.
                  </div>
                </n-popover>
              </div>
              <div>
                <money
                  :money="orderPreviewData.totalAliPostFee / 100 || 0"
                  :is-cny="showCNY"
                ></money>
              </div>
            </div>
            <div
              class="font-[300] mt-[8px] text-[16px] flex text-[#3D3D3D]"
              v-if="computedServiceAmount() >= 1"
            >
              <div class="flex-1">{{ $t("common.服务费") }}</div>
              <div>
                <money
                  :money="computedServiceAmount() / 100 || 0"
                  :is-cny="showCNY"
                ></money>
              </div>
            </div>
            <!-- <div
              class="font-[400] mt-[8px] text-[16px] flex"
              v-if="orderPreviewData.totalDiscount > 0"
            >
              <div class="flex-1">{{ $t("common.订单金额") }}</div>
              <div>
                <money
                  :money="
                    orderPreviewData.totalAmount / 100 +
                    orderPreviewData.totalDiscount / 100
                  "
                  :is-cny="showCNY"
                ></money>
              </div>
            </div> -->

            <div
              class="font-[300] mt-[8px] text-[16px] flex text-[#3D3D3D]"
              v-if="computedAliDiscount() > 1 && !amountLoading"
            >
              <div class="flex-1">{{ $t("common.优惠金额") }}</div>
              <div>
                <money :money="0 - computedAliDiscount() / 100" :is-cny="showCNY"></money>
              </div>
            </div>
            <!-- <div class="font-[400] mt-[8px] text-[16px] flex">
              <div class="flex-1">{{ $t("common.服务费") }} (1%)</div>
              <div>
                <money :money="computedAmount() * 0.01" :is-cny="showCNY"></money>
              </div>
            </div> -->
            <div class="font-[300] mt-[8px] text-[16px] flex text-[#3D3D3D]">
              <div class="flex-1">{{ $t("common.实际支付") }}</div>
              <div>
                <money
                  :money="orderPreviewData.totalAmount / 100"
                  :is-cny="showCNY"
                ></money>
              </div>
            </div>
          </n-spin>
          <div class="mt-[24px]">
            <n-popover
              trigger="manual"
              width="trigger"
              :show="submitShowPopover"
              @clickoutside="submitShowPopover = false"
            >
              <template #trigger>
                <n-popconfirm
                  @positive-click="onClickSubmitOrder"
                  :positive-text="$t('button.确定')"
                  :negative-text="$t('button.取消')"
                >
                  <template #trigger>
                    <n-button
                      size="large"
                      type="primary"
                      class="h-[40px]"
                      block
                      round
                      :loading="amountLoading || submitLoading"
                    >
                      {{ $t("button.立即支付") }}
                    </n-button>
                  </template>
                  {{ $t("confirm.提交订单") }}
                </n-popconfirm>
              </template>
              <span>{{ errorMsg }}</span>
            </n-popover>
          </div>
          <!-- <div class="mt-[24px]">
            <n-button type="primary" class="h-[40px]" block ghost>Place Order</n-button>
          </div> -->
        </div>
      </div>
    </div>

    <n-modal
      v-model:show="showAddressModal"
      preset="dialog"
      class="rounded-[24px]"
      title=""
      style="width: 700px"
      :show-icon="false"
    >
      <div>
        <div class="text-[18px] mb-[16px] font-[500] text-center">
          {{ $t("submitOrder.收货地址") }}
        </div>
        <div>
          <myAddress
            :type="formData.logisticsSelfCare ? 1 : 0"
            @onSelectAddress="onSelectAddress"
            @onRemoveAddress="onRemoveAddress"
          ></myAddress>
        </div>
      </div>
    </n-modal>
    <payLoadingDialog ref="payLoadingDialogRef" v-model:progressModal="progressModal">
    </payLoadingDialog>
  </div>
</template>

<script setup>
import { ref, toRefs } from "vue";
import { Edit, CheckmarkFilled, NextOutline } from "@vicons/carbon";
import { HelpCircle } from "@vicons/ionicons5";
import { useUser } from "@/stores/user";
import { useRouter } from "vue-router";
import myAddress from "@/components/myAddress.vue";
import money from "@/components/money.vue";
import tableGoods from "@/components/tableGoods.vue";
import { preview, createOrder, createPayOrder } from "@/api/order";
import { getUserAddresses } from "@/api/address";
import { useMessage } from "naive-ui";
import payLoadingDialog from "@/components/payLoadingDialog.vue";

const message = useMessage();
const submitResultOrder = ref({});
const showAddressModal = ref(false);
const showSuccessModal = ref(false);
const showSummary = ref(false);
const payLoadingDialogRef = ref();
const tableGoodsRef = ref();
const submitLoading = ref(false);
const submitShowPopover = ref(false);
const errorMsg = ref("");
const showCNY = false;
const progressModal = ref({
  orderId: "",
  loading: false,
  show: false,
  message: "",
});
const { settlementGoods } = toRefs(useUser());
const router = useRouter();
const formData = ref({
  transportType: "",
  buyWay: "alib2b",
  qualityTesting: "40",
  payWay: "payPal",
  insure: false,
  logisticsSelfCare: false,
});
const amountLoading = ref(false);
const chineseAddress = ref({});
const computedAmount = () => {
  return (
    (orderPreviewData.value?.totalAliAmount - orderPreviewData.value?.totalAliPostFee ||
      0) / 100
  );
};
const orderPreviewData = ref({});
const calOrderAmount = async () => {
  if (!settlementGoods.value?.length) return 0;
  let warehouse = {};
  if (formData.value.logisticsSelfCare == false) {
    //alib2b物流
    if (formData.value.transportType == "") {
      return 0;
    }
  } else {
    //自有地址
    if (!address.value) {
      return 0;
    }
    warehouse = {
      fullName: address.value.fullName,
      mobile: address.value.phone,
      phone: address.value.phone,
      postCode: address.value.postCode,
      provinceText: address.value.provinceText,
      cityText: address.value.cityText,
      areaText: address.value.areaText,
      // townText:  address.value.areaText,
      address: address.value.address,
    };
  }
  //预览订单 不需要国外地址
  // if (!address.value?.id) {
  //   return 0;
  // }
  amountLoading.value = true;
  showSummary.value = true;
  const { data } = await preview({
    addressId: parseInt(address.value?.id || "0"),
    shopCarIds: settlementGoods.value.map((x) => x.id),
    insure: formData.value.insure,
    qualityTesting: parseInt(formData.value.qualityTesting),
    transportType: parseInt(formData.value.transportType),
    logisticsSelfCare: formData.value.logisticsSelfCare,
    warehouse: warehouse,
  });
  amountLoading.value = false;
  orderPreviewData.value = data.data;
};
const address = ref({});
const addressList = ref([]);
onMounted(async () => {
  if (!settlementGoods.value?.length) {
    router.push("/cart");
  }
  await getAllAddress();
  if (addressList.value?.length) {
    address.value = addressList.value.find((x) => x.status == 0);
    await calOrderAmount();
  }
});

const getAllAddress = async () => {
  const { data } = await getUserAddresses();
  addressList.value = data.data;
};

// watch(
//   () => settlementGoods.value,
//   (val) => {
//     console.log("%c Line:228 🍢 val", "color:#b03734", val);
//     calOrderAmount();
//   },
//   { immediate: true }
// );

const onUpdateProduct = () => {
  calOrderAmount();
};
const onClickSelectAddress = () => {
  showAddressModal.value = true;
};

const onClickSubmitOrder = async () => {
  // showSummary.value = false;
  // return;
  let warehouse = {};
  if (formData.value.logisticsSelfCare == false) {
    if (formData.value.transportType == "") {
      submitShowPopover.value = true;
      errorMsg.value = window.tt("tips.未选择运输方式");

      // message.warning(window.tt("tips.未选择运输方式"));
      return;
    }
  } else {
    warehouse = {
      fullName: address.value.fullName,
      mobile: address.value.phone,
      phone: address.value.phone,
      postCode: address.value.postCode,
      provinceText: address.value.provinceText,
      cityText: address.value.cityText,
      areaText: address.value.areaText,
      // townText:  address.value.areaText,
      address: address.value.address,
    };
  }

  if (!address.value?.id) {
    submitShowPopover.value = true;
    errorMsg.value = window.tt("tips.未选择收货地址");
    // message.warning(window.tt("tips.未选择收货地址"));
    return;
  }
  if (!settlementGoods.value.length) {
    submitShowPopover.value = true;
    errorMsg.value = window.tt("tips.未选择结算商品");
    // message.warning(window.tt("tips.未选择结算商品"));
    return;
  }

  //判断商品数量是否合法
  submitLoading.value = true;
  let checked = await tableGoodsRef.value.checkSelected();
  // console.log("%c Line:543 🍿 checked", "color:#2eafb0", checked);
  if (!checked) {
    submitShowPopover.value = true;
    errorMsg.value = window.tt("tips.数量不符合设置");
    submitLoading.value = false;
    return;
  }

  progressModal.value.show = true;
  progressModal.value.loading = true;
  progressModal.value.message = window.tt("tips.正在创建订单");

  const { data } = await createOrder({
    addressId: parseInt(address.value.id),
    shopCarIds: settlementGoods.value.map((x) => x.id),
    insure: formData.value.insure,
    qualityTesting: parseInt(formData.value.qualityTesting),
    transportType: parseInt(formData.value.transportType),
    logisticsSelfCare: formData.value.logisticsSelfCare,
    warehouse: warehouse,
  });
  if (data.code != 200) {
    //下单失败
    progressModal.value.error = true;
    progressModal.value.message = window.tt("tips.订单创建失败");
    submitLoading.value = false;
    return;
  }
  submitResultOrder.value = data.data;
  progressModal.value.orderId = data.data.id;
  await payLoadingDialogRef.value.payOrder();
};

const onSelectAddress = async (item) => {
  showAddressModal.value = false;
  address.value = item;
  // if (formData.value.logisticsSelfCare) {
  //   await calOrderAmount();
  // }
  calOrderAmount();
  await getAllAddress();
};

const onRemoveAddress = (item) => {
  if (address.value?.id == item.id) {
    address.value = {};
  }
};

/**
 * 计算商品总价
 */
const computedGoodsAmount = () => {
  return settlementGoods.value.reduce((total, item) => {
    return total + item.price * item.quantity * 100;
  }, 0);
};
/**
 * 计算优惠的金额
 */
const computedAliDiscount = () => {
  if (settlementGoods.value.find((x) => x.cal)) return 0;
  //未计算后台优惠金额
  return (
    computedGoodsAmount() +
    computedServiceAmount() +
    parseInt(orderPreviewData.value.totalAliPostFee) -
    parseInt(orderPreviewData.value.totalAmount)
  );
};
/**
 * 计算服务金额
 */
const computedServiceAmount = () => {
  return (
    (orderPreviewData.value.totalAliAmount - orderPreviewData.value.totalAliPostFee) *
    0.06
  );
};

const onSaveChinsesAddress = (item) => {
  chineseAddress.value = item;
};

const handleChangeLogisticsSelfCare = (value) => {
  address.value = addressList.value?.find(
    (x) => x.type == (value ? 1 : 0) && x.status == 0
  );
  if (address.value) {
    calOrderAmount();
  } else {
    onClickSelectAddress();
  }
};
</script>

<style lang="scss" scoped>
.table-wrapper {
  thead {
    th {
      background-color: var(--sub-color);
      color: white;
      text-align: center;
      height: 32px;
      padding: 0;
    }
  }
  .selected {
    td {
      background-color: #fffbf6;
    }
  }
}
</style>
